//
//  WTRecommendMainViewController.m
//  OneDay
//
//  Created by lanou on 16/1/11.
//  Copyright © 2016年 小明. All rights reserved.
//

#import "WTRecommendMainViewController.h"
#import "WTRequestManager.h"
#import "WTRecommendModel.h"
#import "WTRecommendListCell.h"
#import "WTRecommendListTwoCell.h"
#import <SDCycleScrollView.h>
#import "WTRecommendListModel.h"
#import <MJRefresh.h>
#import <MBProgressHUD.h>





@interface WTRecommendMainViewController ()<SDCycleScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>

// 存放属于scrollView上model的数组
@property (nonatomic, strong) NSMutableArray *pictureArray;

// 轮播图
@property (nonatomic, strong) SDCycleScrollView *scrollView;

// tableView
@property (nonatomic, strong) UITableView *tableView;

// 存放解析完数据后的model的数组
@property (nonatomic, strong) NSMutableArray *listArray;

// 明杰刷新的网络请求的起始位置
@property (nonatomic, assign) NSInteger requestStart;

// 等待数据加载的圈
@property (nonatomic, strong) MBProgressHUD * hud;

@end

@implementation WTRecommendMainViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.view.backgroundColor = [UIColor whiteColor];
      _listArray = [NSMutableArray array];
    
    _requestStart = 0;



    [self requestData];
    
    [self setupData];
    [self setupprogressHud];
    
    // Do any additional setup after loading the view.
}

#pragma mark -- 创建轮播图
- (void)addScrollView
{

    NSMutableArray *imagesURLStrings = [NSMutableArray array];
    NSMutableArray *titleArray = [NSMutableArray array];
    for (WTRecommendModel *model in _pictureArray) {
       
        [imagesURLStrings addObject:model.img];
        [titleArray addObject:model.title];
    }
    CGFloat width = self.view.bounds.size.width;
    
    // 本地加载 -- 创建带标题的图片轮播器
    _scrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, width, 180 * kRelativelength_Y)imageURLStringsGroup:imagesURLStrings];
    // 设置pageControl的位置 右对齐
    _scrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    _scrollView.titlesGroup = titleArray;
    _scrollView.delegate = self;
   
    
    // 模拟加载延迟
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _scrollView.imageURLStringsGroup = imagesURLStrings;
    });

 
    _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    // 把scrollView作为tableView的表头
    _tableView.tableHeaderView = _scrollView;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.view addSubview:_tableView];
    
    // tableView注册cell
    [_tableView registerClass:[WTRecommendListCell class] forCellReuseIdentifier:@"WTRecommendListCell"];
    [_tableView registerClass:[WTRecommendListTwoCell class] forCellReuseIdentifier:@"WTRecommendListTwoCell"];
    
    [self mjRefresh];
   
   
}

#pragma mark --  明杰刷新
- (void)mjRefresh
{
//    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
//    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(setupData)];
//  
//    
//        // 设置普通状态的动画图片
//        [header setImages:@[[UIImage imageNamed:@"m-tuijian"]] forState:MJRefreshStateIdle];
//        // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
//        [header setImages:@[[UIImage imageNamed:@"m-beijing"]] forState:MJRefreshStatePulling];
//        // 设置正在刷新状态的动画图片
//        [header setImages:@[[UIImage imageNamed:@"m-remen"]] forState:MJRefreshStateRefreshing];
    
//       MJRefreshNormalHeader * header = [[MJRefreshNormalHeader alloc]init];
//        // 设置文字
//        [header setTitle:@"Pull down to refresh" forState:MJRefreshStateIdle];
//        [header setTitle:@"Release to refresh" forState:MJRefreshStatePulling];
//        [header setTitle:@"Loading ..." forState:MJRefreshStateRefreshing];
//    
//        // 设置字体
//        header.stateLabel.font = [UIFont systemFontOfSize:15];
//        header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
//    
//        // 设置颜色
//        header.stateLabel.textColor = [UIColor redColor];
//        header.lastUpdatedTimeLabel.textColor = [UIColor blueColor];
//    
//        // 设置header
//        _tableView.mj_header = header;
  
    
#pragma mark -----------------------------------------
    // _requestStart 就是网络请求的开始位置
   
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _requestStart = 0;
        [self setupData];
        [self requestData];
        
    }];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block

        _requestStart++;
        [self setupData];
    }];
}

// 等待网络完成
- (void)setupprogressHud
{
    _hud = [[MBProgressHUD alloc]initWithView:self.view];
    _hud.frame = self.view.bounds;
    _hud.minSize = CGSizeMake(100, 100);
    _hud.mode = MBProgressHUDModeIndeterminate;
    _hud.labelText = @"正在努力加载....";
    [self.view addSubview:_hud];
    
    [_hud show:YES];

}


#pragma mark -- 网络请求
- (void)requestData
{
  
    _pictureArray = [NSMutableArray array];
    // GET请求
    [WTRequestManager requestWithUrlString:@"http://api.wap.miercn.com/api/2.0.3/newlist.php?list=1&page=0&plat=android&proct=mierapp&versioncode=20150807&apiCode=4" parDic:nil method:GET success:^(NSData *data) {
        
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *picsListArray = dictionary[@"picsList"];
        
        // 将字典转化为model,放入数组
        for (NSDictionary *dic in picsListArray) {
            WTRecommendModel *model = [[WTRecommendModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_pictureArray addObject:model];
        }
        [self addScrollView];
    } error:^(NSError *error) {
        
    }];
}

#pragma mark -- 网络请求,放在tableView上
- (void)setupData
{


    NSString * url = [NSString stringWithFormat:@"http://api.wap.miercn.com/api/2.0.3/newlist.php?list=1&page=%@&plat=android&proct=mierapp&versioncode=20150807&apiCode=4",[NSString stringWithFormat:@"%ld",(long)_requestStart]];
    [WTRequestManager requestWithUrlString:url parDic:nil method:GET success:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *newsArray = dic[@"newsList"];
        
        // 在下拉刷新的时候删除掉原来数组的
        if (_requestStart == 1) {
            [_listArray removeAllObjects];
        }
        
        
        for (NSDictionary *oneDic in newsArray) {
            WTRecommendListModel *model = [[WTRecommendListModel alloc]init];
            [model setValuesForKeysWithDictionary:oneDic];
            [_listArray addObject:model];
        }
        
        
        [_tableView reloadData];
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        [_hud hide:YES];
        
    } error:^(NSError *error) {
        
    }];


   
}


#pragma mark -- tableView的代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WTRecommendListModel *model = _listArray[indexPath.row];
    // 判断,如果第一张图片存在,并且第三张图片不存在 是1种情况
    // 其他是另一种情况
    if (![model.picOne isEqualToString:@""] && [model.picThr isEqualToString:@""]) {
        WTRecommendListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WTRecommendListCell" forIndexPath:indexPath];
        cell.model = model;
        return cell;
    }else {
        WTRecommendListTwoCell * cell = [tableView dequeueReusableCellWithIdentifier:@"WTRecommendListTwoCell" forIndexPath:indexPath];
        cell.model = model;
        return cell;
    }
    

}

#pragma mark --  返回每一行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WTRecommendListModel *model = _listArray[indexPath.row];
    if (![model.picOne isEqualToString:@""] && [model.picThr isEqualToString:@""]) {
        return [WTRecommendListCell heightForRow:model];
    }else {
    
       return [WTRecommendListTwoCell heightForRow:model];
    }
    
 
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CATransform3D rotation;
    rotation = CATransform3DMakeRotation( (90.0*M_PI)/180, 0.0, 0.7, 0.4);
    rotation.m34 = 1.0/ -600;
    
    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    cell.layer.shadowOffset = CGSizeMake(10, 10);
    cell.alpha = 0;
    cell.layer.transform = rotation;
    // cell.layer.anchorPoint = CGPointMake(0, 0.5);
    
    
    [UIView beginAnimations:@"rotation" context:NULL];
    [UIView setAnimationDuration:0.8];
    cell.layer.transform = CATransform3DIdentity;
    cell.alpha = 1;
    cell.layer.shadowOffset = CGSizeMake(0, 0);
    [UIView commitAnimations];
    
}

#pragma mark -- SDSDCycleScrollViewDelegate
// 点击轮播图后也会跳转到详情
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    WTRecommendModel * model = _pictureArray[index];
    self.block(model.ID,model.commentNum);
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WTRecommendListModel *model = _listArray[indexPath.row];
    
    self.block(model.ID,model.commentNum);
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
